﻿using Grpc.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using ZhonTai.Admin.Core.Records;

namespace ZhonTai.Admin.Core.Helpers
{
    public static class LicenseValidator
    {
        private static bool _isValid = false;
        private static Timer _licenseTimer;
        private static string licensePath;

        public static bool InitializeLicense()
        {
            string computerName = Environment.UserName;
            licensePath = @$"C:\Users\{computerName}\Desktop\License\license.lic";
            var licenseInfo = ValidateLicenseFile(licensePath);

            if (licenseInfo.Status == "Valid")
            {
                _isValid = true;
                StartLicenseMonitoring();
                return true;
            }
            else
            {
                ShowColorLicenseMessage(licenseInfo.Status,true);
                return false;
            }
        }

        public static void StopMonitoring()
        {
            _licenseTimer?.Dispose();
        }

        private static void CheckLicense(object state)
        {
            if (!File.Exists(licensePath))
            {
                ShowColorLicenseMessage("NotActivated", false);
                return;
            }
            try
            {
                string licenseContent = File.ReadAllText(licensePath);
                LicenseInfo licenseInfo = JsonSerializer.Deserialize<LicenseInfo>(licenseContent);

                if (licenseInfo.ExpireDate < DateTime.Now)
                {
                    ShowColorLicenseMessage("Expired", false);
                }
            }
            catch
            {
                ShowColorLicenseMessage("Invalid", false);
            }
        }

        private static string GetMachineId()
        {
            string cpuId = "UnknownCPU";
            string boardId = "UnknownBoard";

            try
            {
                using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT ProcessorId FROM Win32_Processor"))
                using (ManagementObjectCollection collection = searcher.Get())
                {
                    foreach (ManagementObject obj in collection)
                    {
                        cpuId = obj["ProcessorId"]?.ToString() ?? "UnknownCPU";
                        break;
                    }
                }

                using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT SerialNumber FROM Win32_BaseBoard"))
                using (ManagementObjectCollection collection = searcher.Get())
                {
                    foreach (ManagementObject obj in collection)
                    {
                        boardId = obj["SerialNumber"]?.ToString() ?? "UnknownBoard";
                        break;
                    }
                }
            }
            catch
            {
                cpuId = Environment.MachineName;
                boardId = Environment.UserName;
            }

            return $"{cpuId}_{boardId}".GetHashCode().ToString("X");
        }

        private static string GetMessageByStatus(string status)
        {
            return status switch
            {
                "NotActivated" => "产品未激活，请激活后使用！",
                "Expired" => "软件授权已到期，请联系开发人员！",
                "Invalid" => "授权文件无效，请重新激活！",
                _ => "授权验证失败！"
            };
        }

        private static void ShowColorLicenseMessage(string status, bool isExit)
        {
            string message = GetMessageByStatus(status);
            string title = isExit ? "授权验证失败":"软件到期提示";

            string batContent = $@"
@echo off
chcp 65001 >nul
title {title}

REM 设置窗口大小
mode con: cols=70 lines=12
color 4E

echo.
echo ========================================
echo             授权提示
echo ========================================
echo.
echo    {message}
echo.
echo ========================================
";

            if (isExit)
            {
                batContent += @"
echo    窗口将在5秒后自动关闭...
echo ========================================
timeout /t 5 /nobreak >nul
";
            }
            else
            {
                batContent += @"
echo    按任意键退出程序...
echo ========================================
pause >nul
";
            }

            string tempBatFile = Path.GetTempFileName() + ".bat";
            File.WriteAllText(tempBatFile, batContent, Encoding.UTF8);

            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = tempBatFile,
                    WindowStyle = ProcessWindowStyle.Normal,
                    UseShellExecute = true,
                    CreateNoWindow = false
                }
            };

            process.Start();

            if (isExit)
            {
                process.WaitForExit();
                Thread.Sleep(3000);
                Environment.Exit(1);
            }

            // 延迟删除临时文件
            Task.Delay(10000).ContinueWith(t =>
            {
                try { File.Delete(tempBatFile); } catch { }
            });
        }

        private static void StartLicenseMonitoring()
        {
            // 每5分钟检查一次License状态
            _licenseTimer = new Timer(CheckLicense, null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));
        }

        private static LicenseInfo ValidateLicenseFile(string licensePath)
        {
            try
            {
                if (!File.Exists(licensePath))
                {
                    return new LicenseInfo { Status = "NotActivated" };
                }

                string licenseContent = File.ReadAllText(licensePath);
                LicenseInfo licenseInfo = JsonSerializer.Deserialize<LicenseInfo>(licenseContent);

                // 验证设备信息
                string currentMachineId = GetMachineId();
                if (licenseInfo.MachineId != currentMachineId)
                {
                    return new LicenseInfo { Status = "Invalid" };
                }

                // 验证有效期
                if (licenseInfo.ExpireDate < DateTime.Now)
                {
                    return new LicenseInfo { Status = "Expired" };
                }

                licenseInfo.Status = "Valid";
                return licenseInfo;
            }
            catch
            {
                return new LicenseInfo { Status = "Invalid" };
            }
        }
    }
}
